package utils

import (
	"context"
	"errors"
	"github.com/Sir-yuChen/funAnalyse/global"
	request "github.com/Sir-yuChen/funAnalyse/model/request"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

type JWT struct {
	SigningKey []byte
}

var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

func NewJWT() *JWT {
	//创建一个JWT对象 存储配置文件中 配置为Jwt全局签名
	return &JWT{
		[]byte(global.GVA_CONFIG.JWT.SigningKey),
	}
}

// CreateToken 创建一个token
func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}

// CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.CustomClaims) (string, error) {
	v, err, _ := global.GVA_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
		return j.CreateToken(claims)
	})
	return v.(string), err
}

// CreateClaims 生成token
func (j *JWT) CreateClaims(baseClaims request.BaseClaims) request.CustomClaims {
	claims := request.CustomClaims{
		BaseClaims: baseClaims,
		BufferTime: global.GVA_CONFIG.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 1000,                              // 签名生效时间
			ExpiresAt: time.Now().Unix() + global.GVA_CONFIG.JWT.ExpiresTime, // 过期时间 配置文件
			Issuer:    global.GVA_CONFIG.JWT.Issuer,                          // 签名的发行者
		},
	}
	return claims
}

// ParseToken 校验 token
func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	claims, ok := token.Claims.(*request.CustomClaims)
	if err != nil {
		//ValidationError 令牌无效 匹配具体原因
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				// ValidationErrorMalformed 令牌格式错误
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired  EXP 无效
				return claims, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				// NBF validation failed
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
		//token.Valid 是否有效
		if ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid
	}
}

var ctx = context.Background()

// GetRedisJWT 获取redis 中的token
func GetRedisJWT(key string) (string, error) {
	//redisEnums h
	token, err := global.GVA_REDIS.Get(ctx, key).Result()
	return token, err
}

func RedisJWTExists(key string) (int64, error) {
	//redisEnums h
	res, err := global.GVA_REDIS.Exists(ctx, key).Result()
	return res, err
}
func GetRedisJWTExpiredTime(key string) (time.Duration, error) {
	result, err := global.GVA_REDIS.TTL(ctx, key).Result()
	return result, err
}
func DelRedisJWT(key string) (int64, error) {
	result, err := global.GVA_REDIS.Del(ctx, key).Result()
	return result, err
}

func SetRedisJWT(jwt string, value interface{}) (b bool, err error) {
	// 此处过期时间等于jwt过期时间
	timer := time.Duration(global.GVA_CONFIG.JWT.RedisExpiresTime) * time.Second
	result, err := global.GVA_REDIS.Set(ctx, jwt, value, timer).Result()
	if result == "OK" {
		return true, nil
	}
	return false, err
}
